package org.goyo.main.services.base.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.goyo.common.baseBean.Constants;
import org.goyo.common.exception.DBException;
import org.goyo.common.exception.ServiceException;
import org.goyo.common.utils.DateUtils;
import org.goyo.common.utils.Pager;
import org.goyo.main.domain.dao.base.IMaterialDao;
import org.goyo.main.domain.dao.system.ISysUserDao;
import org.goyo.main.domain.entity.BaseObject;
import org.goyo.main.domain.entity.base.BaseUnitMeasure;
import org.goyo.main.domain.entity.base.Categories;
import org.goyo.main.domain.entity.base.Material;
import org.goyo.main.domain.entity.base.MaterialEntry;
import org.goyo.main.domain.entity.system.SysUser;
import org.goyo.main.domain.excelBean.MaterialExcel;
import org.goyo.main.services.BaseService;
import org.goyo.main.services.base.IMaterialService;
import org.goyo.main.web.controller.system.SessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
@Transactional
public class MaterialServiceImpl extends BaseService implements IMaterialService{
  protected Logger logger = LoggerFactory.getLogger(this.getClass());
	@Resource
	private IMaterialDao materialDao;
	
	@Resource
    private ISysUserDao sysUserDao;

  @Override
  public BaseObject saveOrUpdateInfo(Material info) throws DBException, ServiceException {
    String uuid = null;
    String date = DateUtils.parseDate("yyyy-MM-dd", new Date());
    SysUser user = (SysUser)SessionUtil.getAttribute("user");
    //保存用户数据
    if(info.getUuid() == null || "".equals(info.getUuid())){
        info.setUuid(null);
        info.setStatus(Constants.SAVESTATUS);
        info.setCreateDate(date);
        info.setCreateUser(user);
        info.setAlterDate(date);
        info.setAlterUser(user);
//		alterBillNumber(Material.BIZTYPE, info.getNumber());
        uuid = materialDao.save(info);
    }else{
        info.setAlterDate(date);
        info.setAlterUser(user);
        materialDao.update(info);
        uuid = info.getUuid();
    }
    
    BaseObject obj = new  BaseObject();
    obj.setCreateDate(date);
    obj.setCreateUser(user);
    obj.setAlterDate(date);
    obj.setAlterUser(user);
    obj.setUuid(uuid);
    obj.setStatus(Constants.SAVESTATUS);
    return obj;
}

  @Override
  public void delByUuids(Object[] uuids) throws DBException, ServiceException {for(Object uuid : uuids){
    Material material  = materialDao.get(Material.class, uuid.toString());
    materialDao.delete(material);
}}

  @Override
  public Material findByUuid(String uuid) throws DBException, ServiceException {
    return materialDao.get(Material.class, uuid);
    }

  @Override
  public Pager<Material> findByCondition(String where, Pager pager) throws DBException,
      ServiceException {
    return  materialDao.findByCond(where, pager);
  }

@Override
public Pager<MaterialEntry> findByEntryCondition(String where, Pager pager)
		throws DBException, ServiceException {
	return materialDao.findByEntryCond(where, pager);
}

@Override
public void saveOrUpdateMaterialList(List<MaterialExcel> list) throws DBException, ServiceException {
  SysUser user = (SysUser)SessionUtil.getAttribute("user");
  for (MaterialExcel materialExcel : list) {
    try {
      Material m = null;
      if(!StringUtils.isEmpty(materialExcel.getNumber())){
        m = materialDao.findUnique("from Material where number=? ", new Object[]{materialExcel.getNumber()});
      }
      if(null==m){
        m = new Material();
      }
      m.setName(materialExcel.getName());
      m.setNumber(materialExcel.getNumber());
      m.setBarCode(materialExcel.getBarCode());
      m.setStandard(materialExcel.getStandard());
      m.setSafeStock(materialExcel.getSafeStock());
      m.setMinPurchaseAmount(materialExcel.getMinPurchaseAmount());
      m.setBarCodeManage(coverTrueFalse(materialExcel.getBarCodeManage()));
      m.setLotManage(coverTrueFalse(materialExcel.getLotManage()));
      m.setExpiraDateManage(coverTrueFalse(materialExcel.getExpiraDateManage()));
      m.setExpiraData(materialExcel.getExpiraData());
      m.setCreateDate(materialExcel.getCreateTime());
      m.setAlterDate(materialExcel.getUpdateTime());
      if(!StringUtils.isEmpty(materialExcel.getMatCategoryCode())){
        m.setMatCategory((Categories) materialDao.findUnique("from Categories where number=? ", new Object[]{materialExcel.getMatCategoryCode()}));
      }
      if(!StringUtils.isEmpty(materialExcel.getBaseUnit())){
        m.setBaseUnit((BaseUnitMeasure) materialDao.findUnique("from BaseUnitMeasure where name=?", new Object[]{materialExcel.getBaseUnit()}));
      }
      if(!StringUtils.isEmpty(materialExcel.getExpiraDataUtil())){
        switch (materialExcel.getExpiraDataUtil()) {
          case "年":
            m.setExpiraDataUtil("year");
            break;
          case "季度":
            m.setExpiraDataUtil("quarter");
            break;
          case "月":
            m.setExpiraDataUtil("month");
            break;
          case "星期":
            m.setExpiraDataUtil("week");
            break;
          case "天":
            m.setExpiraDataUtil("day");
            break;
          case "小时":
            m.setExpiraDataUtil("hour");
            break;
          default:
            break;
        }
      }
      if(!StringUtils.isEmpty(materialExcel.getCreateUserName())){
        SysUser su = sysUserDao.findByUserName(materialExcel.getCreateUserName());
        m.setCreateUser(null==su?user:su);
      }
      if(!StringUtils.isEmpty(materialExcel.getUpdateUserName())){
        SysUser su = sysUserDao.findByUserName(materialExcel.getUpdateUserName());
        m.setAlterUser(null==su?user:su);
      }
      
      materialDao.saveOrUpdate(m);
    } catch (Exception e) {
     logger.error(e.getMessage(),e);
     throw e;
    }
   
  }
  
}
private Boolean coverTrueFalse(String value){
  if(!StringUtils.isEmpty(value)){
    if(value.trim().equals("是")){
      return true;
      
    }else if(value.trim().equals("否")){
      return false;
    }
  }
  return false;
}

@Override
public List<MaterialExcel> queryExportDate(String where) throws DBException, ServiceException {
  if(StringUtils.isEmpty(where)){
    where ="";
  }else{
    where = " and "+ where;
  }
  List<MaterialExcel> re = new ArrayList<MaterialExcel>();
  List<Material> list =  materialDao.findObjects("from Material where 1=1 "+ where, null, null);
  if(null!=list && list.size()>0){
    for (Material material : list) {
      MaterialExcel me = new MaterialExcel(material.getNumber(),material.getBarCode(),
          null==material.getMatCategory()?null:material.getMatCategory().getNumber(),
          material.getName(),material.getStandard(),
          null==material.getBaseUnit()?null:material.getBaseUnit().getName(),
          material.getSafeStock(),material.getMinPurchaseAmount(),material.getBarCodeManage(),material.getLotManage(),material.getExpiraDateManage(),material.getExpiraData(),material.getExpiraDataUtil(),
          material.getMatPicture(),
          null==material.getCreateUser()?null:material.getCreateUser().getUsername(),material.getCreateDate(),
          null==material.getAlterUser()?null:material.getAlterUser().getUsername(),material.getAlterDate());
      re.add(me);     
    }
  }else{
    MaterialExcel me = new MaterialExcel();
    me.setNumber("没有数据");
    re.add(me);
  }
  return re;
/*  return materialDao.findByHqlReNewObj("select new org.goyo.main.domain.excelBean.MaterialExcel(number,barCode,matCategory.number,name"
      + ",standard,baseUnit.name,safeStock,minPurchaseAmount,barCodeManage,lotManage,expiraDateManage,expiraData,expiraDataUtil,matPicture,createUser.userName,createDate,alterUser.userName,alterDate) from Material where 1=1 "+ where, null, MaterialExcel.class);*/
}

@Override
public boolean checkNumberUsed(String uuid,String number) throws DBException, ServiceException {
  int i =0;
  try {
    String hql = "";
    if(StringUtils.isEmpty(uuid)){
      hql = "select count(*) from Material where number ='"+number+"'";
    }else{
      hql = "select count(*) from Material where uuid !='"+uuid+"' and number ='"+number+"'";
    }
    List list =  materialDao.findObjects(hql, null, null);
    if(null!=list && list.size()>0&& (Long)list.get(0)>0 ){
     return true;
    }else{
      return false;
    }
  } catch (Exception e) {
    logger.error(e.getMessage(),e);
    return false;
  }
}

}
